package com.shengde.jinwawaforleader.model.homePage.studentproduciton;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.graphics.Bitmap.Config.ARGB_8888;

public class PictureUtil {

    public static List<String> newPicturesData = new ArrayList<>();
    public static String appFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/金娃娃教师版/";

    /**
     * 根据路径删除图片
     *
     * @param path
     */
    public static void deleteTempFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    public static String openCamera(Activity activity, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File path1 = new File(appFilePath);
        if (!path1.exists()) {
            path1.mkdirs();
        }
        File captureFile = new File(path1, System.currentTimeMillis() + ".jpg");
        Uri captureUri = Uri.fromFile(captureFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
        activity.startActivityForResult(intent, requestCode);
        return captureFile.getAbsolutePath().toString();
    }

    /**
     * 刷新图库
     */
    public static void shuaxintuku(Activity activity, String path) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        activity.sendBroadcast(mediaScanIntent);
    }

    /**
     * 计算 bitmap大小，如果超过指定大小，则进行压缩
     *
     * @param srcPath
     * @return
     */
    public static String ImageCompress(String srcPath, String savePath, float hh, float ww, int maxSize) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcPath, opts);
        //根据原始图片的宽高比和期望的输出图片的宽高比计算最终输出的图片的宽和高
        float srcWidth = opts.outWidth;
        float srcHeight = opts.outHeight;
        float maxWidth = ww;
        float maxHeight = hh;
        float srcRatio = srcWidth / srcHeight;
        float outRatio = maxWidth / maxHeight;
        float actualOutWidth = srcWidth;
        float actualOutHeight = srcHeight;
        if (srcWidth > maxWidth || srcHeight > maxHeight) {
            //如果输入比率小于输出比率,则最终输出的宽度以maxHeight为准()
            //比如输入比为10:20 输出比是300:10 如果要保证输出图片的宽高比和原始图片的宽高比相同,则最终输出图片的高为10
            //宽度为10/20 * 10 = 5  最终输出图片的比率为5:10 和原始输入的比率相同

            //同理如果输入比率大于输出比率,则最终输出的高度以maxHeight为准()
            //比如输入比为20:10 输出比是5:100 如果要保证输出图片的宽高比和原始图片的宽高比相同,则最终输出图片的宽为5
            //高度需要根据输入图片的比率计算获得 为5 / 20/10= 2.5  最终输出图片的比率为5:2.5 和原始输入的比率相同
            if (srcRatio < outRatio) {
                actualOutHeight = maxHeight;
                actualOutWidth = actualOutHeight * srcRatio;
            } else if (srcRatio > outRatio) {
                actualOutWidth = maxWidth;
                actualOutHeight = actualOutWidth / srcRatio;
            } else {
                actualOutWidth = maxWidth;
                actualOutHeight = maxHeight;
            }
        }
        int sampleSize = 1;
        if (srcWidth > actualOutWidth || srcHeight > actualOutHeight) {
            int withRatio = Math.round(srcWidth / actualOutWidth);
            int heightRatio = Math.round(srcHeight / actualOutHeight);
            sampleSize = Math.min(withRatio, heightRatio);
        }
        opts.inSampleSize = sampleSize;
        opts.inPreferredConfig = ARGB_8888;//该模式是默认的,可不设
        opts.inPurgeable = true;// 同时设置才会有效
        opts.inInputShareable = true;//。当系统内存不够时候图片自动被回收
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(srcPath, opts);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            return null;//压缩失败
        }
        Bitmap actualOutBitmap = Bitmap.createScaledBitmap(bitmap, (int) actualOutWidth, (int) actualOutHeight, true);
        if (actualOutBitmap != bitmap)
            bitmap.recycle();
        //处理图片旋转问题
        ExifInterface exif;
        try {
            exif = new ExifInterface(srcPath);
            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                matrix.postRotate(90);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                matrix.postRotate(180);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                matrix.postRotate(270);
            }
            actualOutBitmap = Bitmap.createBitmap(actualOutBitmap, 0, 0,
                    actualOutBitmap.getWidth(), actualOutBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        while (baos.toByteArray().length > maxSize && quality >= 10) {
            baos.reset();
            quality -= 10;
            actualOutBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        }
        actualOutBitmap.recycle();
        //将bitmap保存到指定路径
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savePath);
            //包装缓冲流,提高写入速度
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fos);
            bufferedOutputStream.write(baos.toByteArray());
            bufferedOutputStream.flush();
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            return null;
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return savePath;
    }

    /**
     * 图片浏览器 该intent兼容android4.4 的图库，该方法打开的只是图库，不包括下载内容和最新。
     *
     * @return
     */
    public static void startPhotoPickIntent(Activity activity, int requestCode) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(intent, requestCode);
    }

    public static String endtPhotoPickIntent(Activity activity, Intent data) {
        String path = null;
        if (data != null) {
            Uri uriPath = data.getData();
            if (!"".equals(uriPath.getAuthority())) {
                Cursor cursor = null;
                try {
                    cursor = activity.getContentResolver().query(uriPath,
                            new String[]{MediaStore.Images.Media.DATA},
                            null, null, null);
                    cursor.moveToFirst();
                    path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            } else {
                path = uriPath.getPath();
            }
        }
        return path;
    }

    /**
     * 用当前时间给取得的图片命名
     */
    public static String getNewPictureName() {
        return appFilePath + System.currentTimeMillis() + ".jpg";
    }

    public static void addNewPictureNametoList(String path) {
        newPicturesData.add(path);
    }

    public static void deleteAllNewPictures() {
        for (int i = 0; i < newPicturesData.size(); i++) {
            File file = new File(newPicturesData.get(i));
            if (file.exists()) {
                file.delete();
            }
        }
        newPicturesData.clear();
    }
}